const path = require('path');
const fs = require('fs');
import { Plugin } from 'vite'

export function wtmBuildPlugin(): Plugin {
  return {
    name: 'vite:wtmBuild',
    enforce: 'pre',

    buildStart(option) {
      const viewsDir = path.join(__dirname, 'src', 'views');
      console.log(`尝试读取目录: ${viewsDir}`);

      try {
        var files = readDir(viewsDir);
        var views = {};
        files.forEach((val) => {
          const content = fs.readFileSync(val).toString();
          const reg = /\<script.*?name=\"(.*)\"\>/;
          if (reg.test(content)) {
            var m = content.match(reg);
            if (m?.length) {
              // 统一使用正斜杠处理路径
              const normalizedPath = val.replace(/\\/g, '/');
              const normalizedDirname = __dirname.replace(/\\/g, '/');
              const path = normalizedPath
                .replace(`${normalizedDirname}/src/views`, '')
                .replace('/index.vue', '')
                .replace('.vue', '');

              const name = m[1];
              const narray = name.split(';');
              var title = narray[0] ? narray[0] : path.replace(/\//, '_');
              var ishide = (narray.length > 1 && narray[1] == "false") ? true : false;
              var className = narray.length > 2 ? narray[2] : '';
              if (narray.length > 3) {
                className += "," + narray[3];
              }

              views[path] = {
                title: title,
                ishide: ishide,
                className: className
              }
            }
          }
        });

        const outputPath = path.join(__dirname, 'public', 'menu.json');
        fs.writeFileSync(outputPath, JSON.stringify(views));
        console.log(`成功写入菜单文件: ${outputPath}`);
      } catch (error) {
        console.error(`构建错误: ${error.message}`);
        // 避免在构建时中断进程，但记录错误
      }
    }
  }
}

function readDir(dir) {
  try {
    return fs.readdirSync(dir).reduce((files, file) => {
      const filePath = path.join(dir, file);
      const stats = fs.statSync(filePath);

      if (stats.isDirectory()) {
        files = files.concat(readDir(filePath));
      } else if (stats.isFile()) {
        files.push(filePath);
      }
      return files;
    }, []);
  } catch (error) {
    console.error(`读取目录错误 ${dir}: ${error.message}`);
    return [];
  }
}
